#
from Constants import *


'''

convert mouse to grid (back?)

change border colors?

shade image by:
	make new surface
	create partially transparent current image
	blit that on new surf
	edit new surface's colorkey (removes excess color)


'''


class PuzzleBlock(object):
	def __init__(self):
		self.image = pygame.Surface((0,0))
		self.units = []

		self.moving = False
		self.move_start = (0,0)
		self.move_displacement = (0,0)

		self.loc = [0,0]

	def add_unit(self, x, y):
		self.units.append(PuzzleUnit.PuzzleUnit(x, y))

	def make_image(self, grid_size):
		#go through each piece
		#keep track of topleft, width, height
		left = 0
		right = 0
		top = 0
		bottom = 0

		borders = []
		not_borders = []

		#keep track of where borders are/aren't

		first = True
		for u in self.units:
			if first:
				left = u.x
				right = u.x
				top = u.y
				bottom = u.y
				first = False
				continue
			if u.x < left:
				left = u.x
			elif u.x > right:
				right = u.x
			if u.y < top:
				top = u.y
			elif u.y > bottom:
				bottom = u.y

			# for b in ((u.x, u.y, 0), (u.x, u.y, 1), (u.x + 1, u.y, 0), (u.x, u.y + 1, 1)):
				# if b in not_borders:
					# continue
				# elif b in borders:
					# borders.remove(b)
					# not_borders.append(b)
				# else:
					# borders.append(b)

		self.loc = [left * grid_size + PUZZLE_LEFT_MARGIN, top * grid_size + PUZZLE_TOP_MARGIN]
		self.image = pygame.Surface(((right - left + 1) * grid_size, (bottom - top + 1) * grid_size))

		#draw each piece
		for u in self.units:
			subsurf = PUZZLE_IMAGES["unit"].subsurface(int(random.random() * (PUZZLE_UNIT_SIZE - grid_size)), int(random.random() * (PUZZLE_UNIT_SIZE - grid_size)), grid_size, grid_size)
			self.image.blit(subsurf, ((u.x - left) * grid_size, (u.y - top) * grid_size))

		#draw borders
		# for b in borders:
			# w = 2
			# h = 2
			# if b[2] == 0:
				# w = grid_size
			# else:
				# h = grid_size
			# x = int(random.random() * (PUZZLE_BORDER_SIZE - w))
			# y = int(random.random() * (PUZZLE_BORDER_SIZE - h))
			# subsurf = PUZZLE_IMAGES["border"].subsurface(x, y, w, h)

			# self.image.blit(subsurf, (b[0] * GRID_SIZE, b[1] * GRID_SIZE))

	def collide(self, x, y):
		for u in self.units:
			if x == u.x and y == u.y:
				return True
		return False

	def select(self, start):
		self.moving = True
		self.move_start = start

	def in_puzzle(self, x, y, w, h):
		for u in self.units:
			if u.x >= x and u.x < x + w and u.y >= y and u.y < y + h:
				return True
		return False

	def place(self, x, y):
		for u in self.units:
			pass

	def update(self, game):
		if self.moving:
			self.move_displacement = (self.move_start[0] - game.mouse1[0], self.move_start[1] - game.mouse1[1])
			#move pieces?

	def draw(self, camsurf):
		if self.moving:
			pass#half transparent
		camsurf.blit(self.image, self.loc)
